package com.food.restaurantpro.fragments;

import java.util.ArrayList;

import com.food.restaurantpro.R;
import com.food.restaurantpro.activity.MainActivity;
import com.food.restaurantpro.adapters.MenuGridViewAdapter;
import com.food.restaurantpro.database.tables.DishCategoryTable;
import com.food.restaurantpro.objects.DishCategory;
import com.food.restaurantpro.objects.Food;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.TextView;

public class MenuGridViewFragment extends Fragment {

	private TextView tvHeader;
	private ArrayList<DishCategory> mDishCategoryList;
	private GridView mGridView;
	private MenuGridViewAdapter mMenuAdapter;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fragment_menu, container, false);
		
		tvHeader = (TextView)view.findViewById(R.id.tvHeader);
		tvHeader.setText(R.string.tvMenu_Title);
		
		mGridView = (GridView) view.findViewById(R.id.grvDishCategory);
		
		if(mDishCategoryList == null) {
			mDishCategoryList = DishCategoryTable.getAllDishCategory();
		}
		if(mDishCategoryList.size() > 0) {
			mMenuAdapter = new MenuGridViewAdapter(getActivity(), mDishCategoryList);
			mGridView.setAdapter(mMenuAdapter);
			mGridView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position,
						long id) {
					// TODO Auto-generated method stub
					String foodTypeID = ((DishCategory) mGridView.getItemAtPosition(position)).getDishCategoryId();
					((MainActivity) getActivity()).showFoodFragment(foodTypeID);
				}
			});
		}
		return view;
	}
	
	@Override
	public void onDestroy() {
		// TODO delete image and cache de giai phong bo nho
		super.onDestroy();
		mGridView.setAdapter(null);
		if(mMenuAdapter != null) {
			mMenuAdapter.clearMemoryCache();
		}
		if(mDishCategoryList != null) {
			mDishCategoryList.clear();
			mDishCategoryList = null;
		}
		Runtime.getRuntime().gc();
	}
}
